<?php
    
    
class SiteController extends Controller
{
	/**
	 * Declares class-based actions.
	 */
        public function actions()
	{
		return array(
			// captcha action renders the CAPTCHA image displayed on the contact page
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xFFFFFF,
			),
			// page action renders "static" pages stored under 'protected/views/site/pages'
			// They can be accessed via: index.php?r=site/page&view=FileName
			'page'=>array(
				'class'=>'CViewAction',
			),
		);
	}
            
                    //ext facebook
//                    protected function afterRender($view, &$output) {
//                        parent::afterRender($view,$output);
//                        //Yii::app()->facebook->addJsCallback($js); // use this if you are registering any $js code you want to run asyc
//                        Yii::app()->facebook->initJs($output); // this initializes the Facebook JS SDK on all pages
//                        Yii::app()->facebook->renderOGMetaTags(); // this renders the OG tags
//                        return true;
//                   }
	/**
	 * This is the default 'index' action that is invoked
	 * when an action is not explicitly requested by users.
	 */
	 public function actionIndex()
	{
                        // renders the view file 'protected/views/site/index.php'
                        // using the default layout 'protected/views/layouts/main.php'
                        //$this->render('index');
                        $this->layout = FALSE;
                        $model = new SalePointForm();
                        $modelcontact = new ContactForm();
                        $modelnews = new NewsForm();
                        $modellogin = new LoginForm();
                        $modeltypebusiness = new TypeBusinessForm();
                        $modelregister = new RegisterForm();
                        $modelforgot = new ForgotForm();
//                        if(isset($_POST['RegisterForm'])) {      
                            if(isset($_POST['ajax']) && $_POST['ajax']==='register-form'){
                                    echo CActiveForm::validate($modelregister);
                                    Yii::app()->end();
                            }
                            // collect user input data
                            if(isset($_POST['RegisterForm'])){
                                    $modelregister->attributes=$_POST['RegisterForm'];
                                    $modelregister->activate_key=sha1(mt_rand(10000, 99999).time().$modelregister->email);
                                    $modelregister->activate_status = 0;
                                    // validate user input and redirect to the previous page if valid
                                    if($modelregister->validate() && $modelregister->register()) {
                                        $this->actionSendEmailActive($modelregister->email, $modelregister->activate_key, 0);
                                        echo "<script type='text/javascript'>";
                                        echo "alert('Bạn đã tạo thành công tài khoản. Xin vui lòng kích hoạt tài khoản trước khi đăng nhập.');";
                                        echo "alert('Email đã được gửi cho bạn, vui lòng kiểm tra hộp thư (inbox, spam,...)');";
                                        echo "window.location.href = '".Yii::app()->homeUrl."';";                           
                                        echo "</script>";
//                                        $this->redirect(Yii::app()->baseUrl.'/index.php/site/registeralert?key='.FALSE);
                                       }         
                           }
//                        }
                        // if it is ajax validation request
                        if(isset($_POST['ajax']) && $_POST['ajax']==='login-form'){
                                echo CActiveForm::validate($modellogin);
                                Yii::app()->end();
                        }
                        // collect user input data
                        if(isset($_POST['LoginForm'])){
                                $modellogin->attributes=$_POST['LoginForm'];
                                // validate user input and redirect to the previous page if valid
                                if($modellogin->validate() && $modellogin->login()) {
                                                                                //$this->redirect(Yii::app()->user->returnUrl);
                        //                                                            $this->redirect(Yii::app()->baseUrl);     
                                                                        $this->refresh();
                                                                    }                                                                   
                        }                                      
                        if (isset($_POST['ContactForm'])) {
                                $modelcontact->attributes=$_POST['ContactForm'];
                                if($modelcontact->validate() && $modelcontact->contact()){
                                    //                                $this->redirect('index.php/site/main');     
//                               Yii::app()->user->setFlash('contact','Thank you for contacting us. We will respond to you as soon as possible.');
                                $this->refresh();
                                }
                        }
                        if (isset($_POST['ForgotForm'])) {
                            $modelforgot->attributes=$_POST['ForgotForm'];
                            if ($modelforgot->forgot()) {                          
                                echo "<script type='text/javascript'>";
                                echo "alert('Gửi mail thành công, vui lòng kiểm tra hộp thư (inbox, spam,...).');";
                                echo "window.location.href = '".Yii::app()->homeUrl."';";                           
                                echo "</script>";
                            }
                        }
                        
                        $rows_search = '';
                        //Searching
                        if(isset($_POST['mode']) && $_POST['mode'] == 'search') {
                            $city_code = $_POST['city'];
                            $city = $model->arrArea[$city_code-1];
                            $district = $_POST['district'];
                            $type_business = $_POST['type_business'];
                            $rows_search = $model->searchSalePoint($city, $district, $type_business);
//                            var_dump($rows_search);
//                            exit;
                        } 
                        //trường dữ liệu
                        $rows_salepoint = $model->getDatabase();
                        // dòng dữ liệu
                        if (isset(Yii::app()->session['login']) && Yii::app()->session['saleId'] != 0)
                            $row_salepoint = $model->getSalePoint(Yii::app()->session['saleId']);
                        else
                            $row_salepoint ='';
                        //xét 2 trường hợp không có data và chỉ có 1 dòng dữ liệu
                        $rows_typebusiness = $modeltypebusiness->getDatabase();
                        if (empty($rows_typebusiness)){
                            $rows_typebusiness[0]['id'] = 1;
                            $rows_typebusiness[0]['name'] = 'General';
                        }
                        //xử lý rating
                        $row_salepoint_rating = $this->bubbleSort($rows_salepoint, 'sale_rating');
                        //xử lý news time
                        $row_news = $modelnews->getDatabase();
                        $row_news = $this->bubbleSort($row_news, 'news_time');
                        
                        $this->render('index',array('data' => $rows_salepoint,
                            'model' => $modelcontact,
                            'row' => $row_salepoint, // chỉ 1 dòng
                            'data_news' => $row_news,
                            'modellogin' => $modellogin,
                            'data_business' => $rows_typebusiness,
                            'modelregister' => $modelregister,
                            'data_rating' => $row_salepoint_rating,
                            'modelforgot' => $modelforgot,
                            'data_search' => $rows_search
                            ));
	}
        public function actionGetlstDistricts() {
            $model_salepoint = new SalePointForm();
            $arrDistrict = array();
            if (isset($_GET['city'])) {
                $city = $_GET['city'];
                if ($city=='1') {
                    $arrDistrict = $model_salepoint->arrDistrict[0];
                } elseif ($city=='2') {
                    $arrDistrict = $model_salepoint->arrDistrict[1];
            }
            }
            $district = json_encode($arrDistrict);
            echo $district;
        }




        public function actionCategory()
	{
		// renders the view file 'protected/views/site/index.php'
		// using the default layout 'protected/views/layouts/main.php'
                    if($this->checkLogin()) {
                            $this->render('category');                      
                    }

	}
                    public function actionCategoryAdd() {
                        $model= new CategoryForm();
                        if(isset($_POST['CategoryForm'])) {
                            //upload model with yii contruct
                              $model->attributes=$_POST['CategoryForm'];
//                                $rnd = rand(0,9999);  // generate random number between 0-9999
//                                $uploadedFile=CUploadedFile::getInstance($model,'image');
//                                $fileName = "{$rnd}-{$uploadedFile}";  // random number + file name
//                                $model->image = $fileName;
                              //elfinder (update image to CategoryForm)
                                $link_image =  $_POST['CategoryForm']['image'];
                                 $part = explode ('/', $link_image);
                                 $model->image = $part[count($part)-1];
                                     
                                if($model->add()) {                                             
                                     //upload model with yii contruct
//                                    $uploadedFile->saveAs(Yii::app()->basePath.'/../files/'.$fileName);
                                    $this->redirect('../site/category');     
                        }
                        }
                        if($this->checkLogin()) {
                             $this->render('categoryadd',array('model'=>$model)); 
                        }                        
                    }
                    public function actionCategoryEdit() {
                        $model= new CategoryForm();  
                            if(isset($_POST['CategoryForm']))
                            {
                                //only if use loadModel
//                                $_POST['StoreForm']['image'] = $model->image;
    
                                $model->attributes=$_POST['CategoryForm'];
                                    
                                 //elfinder (update image to CategoryForm)
                                $link_image =  $_POST['CategoryForm']['image'];
                                 $part = explode ('/', $link_image);
                                 $model->image = $part[count($part)-1];
                                     
                                //upload model with yii contruct
//                                $uploadedFile=CUploadedFile::getInstance($model,'image');
//                                 if(!empty($uploadedFile))  // check if uploaded file is set or not
//                                    {
//                                        $rnd = rand(0,9999);  // generate random number between 0-9999
//                                        $fileName = "{$rnd}-{$uploadedFile}";
//                                        $model->image = $fileName;
//                                        //if only use loadModel
////                                        $_POST['StoreForm']['image'] =$fileName;
//                                    }
                                if($model->edit())
                                {
                                    //upload model with yii contruct
//                                   if(!empty($uploadedFile))  // check if uploaded file is set or not
//                                    {
//                                        $uploadedFile->saveAs(Yii::app()->basePath.'/../files/'.$fileName);
//                                    }                                
                                   $this->redirect('../site/category');
                                }
                            }
                            if($this->checkLogin()) {
                            $this->render('categoryedit',array('model'=>$model));                                
                            }                    
                    }
                    public function actionItem() {
                    if($this->checkLogin()) {   
                            $this->render('item');                    
                    }
	}
                    public function actionItemAdd() {
                        $model= new ItemForm();
                        if(isset($_POST['ItemForm'])) {
                            //upload model with yii contruct
                              $model->attributes=$_POST['ItemForm'];
//                                $rnd = rand(0,9999);  // generate random number between 0-9999
//                                $uploadedFile=CUploadedFile::getInstance($model,'image');
//                                $fileName = "{$rnd}-{$uploadedFile}";  // random number + file name
//                                $model->image = $fileName;
                              //elfinder (update image to ItemForm)
                                $link_image =  $_POST['ItemForm']['image'];
                                 $part = explode ('/', $link_image);
                                 $model->image = $part[count($part)-1];
                                 //
//                                     $model->sub_image = json_encode($this->list_image);
//                                     echo var_dump($link_image);
//                                     break;
                                if($model->add()) {                                             
                                     //upload model with yii contruct
//                                    $uploadedFile->saveAs(Yii::app()->basePath.'/../files/'.$fileName);
//                                    setTimeout("location.href = '../site/item';",5000);
                                    $this->redirect('../site/item');     
                        }
                        }
                        if($this->checkLogin()) {
                        $this->render('itemadd',array('model'=>$model)); 
                        }
                    }
                    public function actionItemEdit() {
                        $model= new ItemForm();
                            if(isset($_POST['ItemForm'])) {
                               //only if use loadModel
//                                $_POST['StoreForm']['image'] = $model->image;
    
                                $model->attributes=$_POST['ItemForm'];
                                    
                                 //elfinder (update image to ItemForm)
                                $link_image =  $_POST['ItemForm']['image'];
                                 $part = explode ('/', $link_image);
                                 $model->image = $part[count($part)-1];
                                     
                                //upload model with yii contruct
//                                $uploadedFile=CUploadedFile::getInstance($model,'image');
//                                 if(!empty($uploadedFile))  // check if uploaded file is set or not
//                                    {
//                                        $rnd = rand(0,9999);  // generate random number between 0-9999
//                                        $fileName = "{$rnd}-{$uploadedFile}";
//                                        $model->image = $fileName;
//                                        //if only use loadModel
////                                        $_POST['StoreForm']['image'] =$fileName;
//                                    }
                                if($model->edit())
                                {
                                    //upload model with yii contruct
//                                   if(!empty($uploadedFile))  // check if uploaded file is set or not
//                                    {
//                                        $uploadedFile->saveAs(Yii::app()->basePath.'/../files/'.$fileName);
//                                    }         
                                   $this->redirect('../site/item');
                                }
                            }
                            if($this->checkLogin()) {
                        $this->render('itemedit',array('model'=>$model));                        
                            }
                    }
                    public function actionOrder() {
                    if($this->checkLogin()) {
                            $this->render('order');                     
                   }
	}  
	/**
	 * This is the action to handle external exceptions.
	 */
	public function actionError()
	{
		if($error=Yii::app()->errorHandler->error)
		{
			if(Yii::app()->request->isAjaxRequest)
				echo $error['message'];
			else
				$this->render('error', $error);
		}
	}
            
	/**
	 * Displays the contact page
	 */
	public function actionContact() {
		$model=new ContactForm();
                                        if($model->contact()){
                                            Yii::app()->user->setFlash('contact','Thank you for contacting us. We will respond to you as soon as possible.');
				$this->refresh();
                                        $this->redirect('index.php/site/main');     
                                        }
		/*if(isset($_POST['ContactForm']))
		{
			$model->attributes=$_POST['ContactForm'];
			if($model->validate())
			{
				$name='=?UTF-8?B?'.base64_encode($model->name).'?=';
				$subject='=?UTF-8?B?'.base64_encode($model->subject).'?=';
				$headers="From: $name <{$model->email}>\r\n".
					"Reply-To: {$model->email}\r\n".
					"MIME-Version: 1.0\r\n".
					"Content-type: text/plain; charset=UTF-8";
                                            
				//mail(Yii::app()->params['adminEmail'],$subject,$model->body,$headers);
                                Yii::import('ext.yii-mail.YiiMailMessage');
                                $message = new YiiMailMessage;
                                $message->setBody($model->body, 'text/html');
                                $message->subject = $subject;
                                $message->addTo(Yii::app()->params['adminEmail']);
                                $message->from = $model->email;
                                Yii::app()->mail->send($message);	
                                Yii::app()->user->setFlash('contact','Thank you for contacting us. We will respond to you as soon as possible.');
				$this->refresh();
			}
		}
                 		$this->render('contact',array('model'=>$model));*/
	}
            
	/**
	 * Displays the login page
	 */
	public function actionLogin()
	{
		$model=new LoginForm;
		// if it is ajax validation request
		if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
		// collect user input data
		if(isset($_POST['LoginForm']))
		{
			$model->attributes=$_POST['LoginForm'];
			// validate user input and redirect to the previous page if valid
			if($model->validate() && $model->login()) {
                                                                        //$this->redirect(Yii::app()->user->returnUrl);
                                                            $this->redirect(Yii::app()->baseUrl);      
                                                            }                                                   
                                        }
                                            
                if (isset($_POST['ForgotForm'])) {
                //forgot form by dung3625@gmail.com
                $model = new ForgotForm;
                if(isset($_POST['ajax']) && $_POST['ajax']==='forgot-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
                    
		// collect user input data
		if(isset($_POST['ForgotForm']))
		{
			$model->attributes=$_POST['ForgotForm'];
			// validate user input and redirect to the previous page if valid
                                                          if($model->validate() && $model->forgot()) {
                                                                        $this->redirect("../site/forgot");
                                                            }
		}
                }
                $modelregister = new RegisterForm();
                if(isset($_POST['RegisterForm'])) {      
                //register form by dung3625@gmail.com
//                $model = new RegisterForm();
                    if(isset($_POST['ajax']) && $_POST['ajax']==='register-form')
                    {
                            echo CActiveForm::validate($modelregister);
                            Yii::app()->end();
                    }
                    // collect user input data
                    if(isset($_POST['RegisterForm']))
                    {
                            $modelregister->attributes=$_POST['RegisterForm'];
                            $modelregister->activate_key=sha1(mt_rand(10000, 99999).time().$modelregister->email);
                            $modelregister->activate_status = 0;
                            // validate user input and redirect to the previous page if valid
                            if($modelregister->validate() && $modelregister->register()) {
                                $this->actionSendEmailActive($modelregister->email, $modelregister->activate_key);
                                $this->redirect(Yii::app()->baseUrl.'/index.php/site/registeralert?key='.FALSE);

                               }         
                   }
                }
                                      $this->layout = false;//clear layout
		// display the login form
		$this->render('login',array('model'=>$model, 'modelregister' =>$modelregister));
	}
                    public function actionSendEmailActive($email, $key, $key_layout) {
                        //key_layout: dùng dể thay đổi giao diện.
                        // 1: giao diện
                        // 0: popup
                        $to = $email;
                        $message = new YiiMailMessage;
                        $subject = "Your Activation Link";       
                        $content = 
                                "<html><body>Please click this below to activate your membership<br />".
                                            Yii::app()->createAbsoluteUrl('site/activate', array('email' => $to,'key'=>$key, 'key_layout'=>$key_layout))
                                ."<br/>Thanks you." 
                                ."</body></html>";
                        $message->setBody($content, 'text/html');
                        $message->subject = $subject;
                        $message->addTo($to);
                        $message->setFrom(array(Yii::app()->params['adminEmail'] => 'Admin Order System'));
                        Yii::app()->mail->send($message);
        }
                    public function actionActivate() {
                    $email = Yii::app()->request->getQuery('email');
                    $key = Yii::app()->request->getQuery('key');
                    $key_layout = Yii::app()->request->getQuery('key_layout');
                    $model = new RegisterForm();
                    if(isset($email) && isset($key)) {
                        if($model->checkActivate($email, $key)) {
                            $model->activate_status = 1;
                            if ($model->activate($email)) {
                                if($key_layout == 1)
                                    $this->redirect(Yii::app()->request->baseUrl.'/index.php/site/registeralert?key='.true);
                                elseif ($key_layout == 0) {
                                    echo "<script type='text/javascript'>";
                                    echo "alert('Successfully activate your account.');";
                                    echo "window.location.href = '".Yii::app()->homeUrl."';";                           
                                    echo "</script>";
                                }
                            }
                            else {
                                echo 'error';
                                }
                                }
                                else { echo "error";}
                                }
                                }
        /**
	 * Logs out the current user and redirect to homepage.
	 */
	public function actionLogout() {
                                      unset(Yii::app()->session['login']);
                                      Yii::app()->session->destroy();
		Yii::app()->user->logout();
		$this->redirect(Yii::app()->homeUrl);
	}
            
                    public function actionForgot() {
                        $this->render('forgot'); 
                    }
                    public function actionRegisterAlert() {
                        $this->render('registeralert'); 
                    }
                    public function actionRegistration() {
                        $model = new RegisterForm();
                        if(isset($_POST['RegisterForm'])) {      
//                            if(isset($_POST['ajax']) && $_POST['ajax']==='register-form')
//                            {
//                                    echo CActiveForm::validate($model);
//                                    Yii::app()->end();
//                            }
                            // collect user input data
                            if(isset($_POST['RegisterForm']))
                            {
                                    $model->attributes=$_POST['RegisterForm'];
                                    $model->activate_key=sha1(mt_rand(10000, 99999).time().$model->email);
                                    $model->activate_status = 0;
                                    // validate user input and redirect to the previous page if valid
                                    if($model->register()) {
                                        $this->actionSendEmailActive($model->email, $model->activate_key, 1);
                                        $this->redirect(Yii::app()->baseUrl.'/index.php/site/registeralert?key='.'0');
                                       }         
                           }
                        }
                        $this->render('registration',array('model'=>$model));
                    }

                    public function actionStore() {
                        if($this->checkLogin()) {
                            $this->render('store');                       
                        }
                    }
                    public function actionStoreAdd() {
                        $model=new StoreForm();
                        if(isset($_POST['StoreForm'])) {
                              //upload model with yii contruct
                              $model->attributes=$_POST['StoreForm'];
//                                $rnd = rand(0,9999);  // generate random number between 0-9999
//                                $uploadedFile=CUploadedFile::getInstance($model,'image');
//                                $fileName = "{$rnd}-{$uploadedFile}";  // random number + file name
//                                $model->image = $fileName;
                              //elfinder (update image to StoreForm)
                                $link_image =  $_POST['StoreForm']['image'];
                                 $part = explode ('/', $link_image);
                                 $model->image = $part[count($part)-1];
                                if($model->add()) {                                             
                                     //upload model with yii contruct
//                                    $uploadedFile->saveAs(Yii::app()->basePath.'/../files/'.$fileName);
                                                                     $this->redirect('../site/store');     
                        }
                    }
                    if($this->checkLogin()) {
                        $this->render('storeadd',array('model'=>$model)); 
                    }
                    }
                        
                    public function actionStoreEdit() {
                           $model= new StoreForm();
                            if(isset($_POST['StoreForm'])) {
                                //only if use loadModel
//                                $_POST['StoreForm']['image'] = $model->image;
    
                                $model->attributes=$_POST['StoreForm'];
                                    
                                 //elfinder (update image to StoreForm)
                                $link_image =  $_POST['StoreForm']['image'];
                                 $part = explode ('/', $link_image);
                                 $model->image = $part[count($part)-1];
                                     
                                //upload model with yii contruct
//                                $uploadedFile=CUploadedFile::getInstance($model,'image');
//                                 if(!empty($uploadedFile))  // check if uploaded file is set or not
//                                    {
//                                        $rnd = rand(0,9999);  // generate random number between 0-9999
//                                        $fileName = "{$rnd}-{$uploadedFile}";
//                                        $model->image = $fileName;
//                                        //if only use loadModel
////                                        $_POST['StoreForm']['image'] =$fileName;
//                                    }
                                if($model->edit())
                                {
                                    //upload model with yii contruct
//                                   if(!empty($uploadedFile))  // check if uploaded file is set or not
//                                    {
//                                        $uploadedFile->saveAs(Yii::app()->basePath.'/../files/'.$fileName);
//                                    }         
                                   $this->redirect('../site/store');
                                }
                                    
                            }
                            if($this->checkLogin()) {
                            $this->render('storeedit',array('model'=>$model)); 
                            }
                    }
                    public function actionNews() {
                       if($this->checkLogin()) {
                            $this->render('news'); 
                       }
                    }
                    public function actionNewsAdd() {
                        $model= new NewsForm();
                        if(isset($_POST['NewsForm'])) {
                              //upload model with yii contruct
                              $model->attributes=$_POST['NewsForm'];
//                                $rnd = rand(0,9999);  // generate random number between 0-9999
//                                $uploadedFile=CUploadedFile::getInstance($model,'image');
//                                $fileName = "{$rnd}-{$uploadedFile}";  // random number + file name
//                                $model->image = $fileName;
                              //elfinder (update image to NewsForm)
                                $link_image =  $_POST['NewsForm']['image'];
                                 $part = explode ('/', $link_image);
                                 $model->image = $part[count($part)-1];
                                if($model->add()) {                                             
                                     //upload model with yii contruct
//                                    $uploadedFile->saveAs(Yii::app()->basePath.'/../files/'.$fileName);
                                    $this->redirect('../site/news');     
                        }
                        }
                        if($this->checkLogin()) {
                            $this->render('newsadd',array('model'=>$model)); 
                        }
                    }
                    public function actionNewsEdit() {
                        $model= new NewsForm();   
                            if(isset($_POST['NewsForm']))   {
                                //only if use loadModel
//                                $_POST['NewsForm']['image'] = $model->image;
    
                                $model->attributes=$_POST['NewsForm'];
                                    
                                 //elfinder (update image to NewsForm)
                                $link_image =  $_POST['NewsForm']['image'];
                                 $part = explode ('/', $link_image);
                                 $model->image = $part[count($part)-1];
                                     
                                //upload model with yii contruct
//                                $uploadedFile=CUploadedFile::getInstance($model,'image');
//                                 if(!empty($uploadedFile))  // check if uploaded file is set or not
//                                    {
//                                        $rnd = rand(0,9999);  // generate random number between 0-9999
//                                        $fileName = "{$rnd}-{$uploadedFile}";
//                                        $model->image = $fileName;
//                                        //if only use loadModel
////                                        $_POST['NewsForm']['image'] =$fileName;
//                                    }
                                if($model->edit())
                                {
                                    //upload model with yii contruct
//                                   if(!empty($uploadedFile))  // check if uploaded file is set or not
//                                    {
//                                        $uploadedFile->saveAs(Yii::app()->basePath.'/../files/'.$fileName);
//                                    }         
                                   $this->redirect('../site/news');
                                }     
                            }
                            if($this->checkLogin()) {
                                $this->render('newsedit',array('model'=>$model));                        
                            }
                    }
                    private function checkLogin() {
                        if (Yii::app()->session['login']) {
                            return true;
                        }
                        else {
                            $this->layout = false;//clear layout
                                // display the login form
                            $this->redirect(Yii::app()->homeUrl);                                              
                            }
                    }
                    public function actionSalePoint() {
                        $model_salepoint = new SalePointForm();
                                $salePoint = $model_salepoint->getSalePoint(Yii::app()->session['saleId']);
                        if($this->checkLogin()) {
                            $this->render('salepoint',  array('data_typebusiness'=>$this->actionGetTypeBusiness(),
                                'data_salepoint'=> $salePoint
                                ));
                        }
                    }
                    public function actionSalePointEdit() {
                        $model = new SalePointForm();
                        $model_type_business = new TypeBusinessForm();
                        $rows_typebusiness = $model_type_business->getDatabase();
//                        if (empty($rows_typebusiness)){
//                            $rows_typebusiness[0]['id'] = 1;
//                            $rows_typebusiness[0]['name'] = 'General';
//                        } elseif (!is_array($rows_typebusiness)) {
//                            $rows_typebusiness[0]['id'] = $rows_typebusiness['id'];
//                            $rows_typebusiness[0]['name'] = $rows_typebusiness['name'];
//                        }
                        
                        if (isset($_POST['SalePointForm'])) {
                            $model->attributes = $_POST['SalePointForm'];
                            //elfinder
                            $image = $_POST['SalePointForm']['sale_image'];
                            $part = explode('/', $image);
                            $model->sale_image = $part[count($part)-1];
                            
                            if (isset($model->sale_area)) {
                                if ($model->sale_area == '1') {
                                    $model->sale_area = $model->arrArea['0'];
                                    } elseif ($model->sale_area == '2') {
                                        $model->sale_area = $model->arrArea['1'];
                                        }            
                                        }       
                            if($model->edit()) 
                                $this->redirect('../site/salepoint');
                        }
                        $rows_salepoint[0] = $model->getSalePoint(Yii::app()->session['saleId']);
//                        var_dump($rows_salepoint);
//                        var_dump($model);
//                        var_dump($rows_typebusiness);
//                        exit;
                        if ($this->checkLogin())
                        $this->render('salepointedit',array('model'=>$model,
                            'data_business' => $rows_typebusiness,
                            'rows_salepoint' => $rows_salepoint
                            ));
                    }
                    public function actionSalePointAdd() {
                        $model = new SalePointForm();
                        $modelTypeBussiness = new TypeBusinessForm();
                        $modelcontact = new ContactForm();

                        if (isset($_POST['ContactForm'])) {
                                $modelcontact->attributes=$_POST['ContactForm'];
                                if($modelcontact->validate() && $modelcontact->contact()){
                                    //                                $this->redirect('index.php/site/main');     
                               Yii::app()->user->setFlash('contact','Thank you for contacting us. We will respond to you as soon as possible.');
                                $this->refresh();
                                }
                        }
                        //1 row sale point with user
                        if (isset(Yii::app()->session['login']) && Yii::app()->session['saleId'] != 0)
                            $row_salepoint = $model->getSalePoint(Yii::app()->session['saleId']);
                        else
                            $row_salepoint ='';
                        //xét 2 trường hợp không có data và chỉ có 1 dòng dữ liệu
                        $rows_typebusiness = $modelTypeBussiness->getDatabase();
                        if (empty($rows_typebusiness)){
                            $rows_typebusiness[0]['id'] = 1;
                            $rows_typebusiness[0]['name'] = 'General';
                        } elseif (!is_array($rows_typebusiness)) {
                            $rows_typebusiness[0]['id'] = $rows_typebusiness['id'];
                            $rows_typebusiness[0]['name'] = $rows_typebusiness['name'];
                        }
                        if (isset($_POST['SalePointForm'])) {
                            $model->attributes = $_POST['SalePointForm'];
//                            //elfinder
//                            $image = $_POST['SalePointForm']['sale_image'];
//                            $part = explode('/', $image);
//                            $model->sale_image = $part[count($part)-1];
                       if (isset($model->sale_area)) {
                           if ($model->sale_area == '1') {
                               $model->sale_area = $model->arrArea['0'];
                               } elseif ($model->sale_area == '2') {
                                   $model->sale_area = $model->arrArea['1'];
                                   }            
                                   }                            
                            if($model->add()) {
                                $this->actionActiveSalePoint();
                                echo "<script type='text/javascript'>";
                                echo "alert('Bạn đã tạo thành công thương hiệu của mình. 
                                                 Xin vui lòng đợi nhà quản lý cấp phép.');";
                                echo "window.location.href = '".Yii::app()->homeUrl."';";                           
                                echo "</script>";
//                                die();
//                                $this->redirect(Yii::app()->homeUrl);                                     
                            }
                        }
//                        $model->arrArea;
                        if ($this->checkLogin()) {
                            $this->layout = FALSE;
                            $this->render('salepointadd',  array('model'=>$model,
                                'row' => $row_salepoint, // chỉ 1 dòng
                                'data_business' => $rows_typebusiness,
                                'modelcontact' => $modelcontact,
                            ));                            
                        }
                    }
                    public function actionActiveSalePoint() {
                        $objAdmin = new AdminForm();
                        $arrAdmin = array();
                        $arrAdmin = $objAdmin->getDatabase();
                        $ret = array();
                        $subject = "Active Sale Point";
                        $message = "<html><body>You have a request active sale point<br />Please check! <br /> <br />".
                                            Yii::app()->createAbsoluteUrl('site/saleActivate',array('key' => Yii::app()->session['saleId']))
                                ."<br/><br />Thanks you." 
                                ."</body></html>";
                        foreach ($arrAdmin as $key => $value) {
                            $this->actionSendEmail($value['email'], $subject, $message);
                            $ret[] = true;
                        }
                        return $ret;
                    }
                    public function actionSaleActive() {
                        $model_salepoint = new SalePointForm();
                        $sale_id = Yii::app()->request->getQuery('key');
                        $model_salepoint->activeSalepoint($sale_id);
                    }
                    public function actionSendEmail($to_email, $subject, $message) {
                        $mail = new YiiMailMessage;
                        $mail->setBody("To {$to_email}: <br /> <br />
                            {$message}", 'text/html');
                        $mail->subject =  $subject;
                        $mail->addTo($to_email);
                        $mail->setFrom(array(Yii::app()->params['adminEmail'] => 'System'));    //Yii::app()->params['adminEmail'];
                        return Yii::app()->mail->send($mail);    
                    }

                    public function actionUploadImage($id)    {
                        $rowid = $id;
                        $model = new UploadImage();
                            
//                        $list_image=array();
                        $list_image = json_decode($model->GetDatabase($rowid));
                        $file = $_FILES['file'];
                        $url = '';
                        if (!$file['name'] || $file['name'] != null) {
                        //    $img = UploadImage::upload_files($file);
                            $img = $model->upload_files($file);  
                                    $url = $img[0]['url'];
                        }
                        //if (is_array($list_image))
                        //        $list_image = json_decode($list_image);
                        //else $list_image = array();
                        if (empty($list_image) || !is_array($list_image)) $list_image = array();
                                $count = array_push($list_image, $img[0]['name']);
                        //        echo var_dump($list_image);
                                $model->SaveImage($list_image, $rowid);
                                        $html = '<li>
                                                                        <div>
                                                                            <img width="200" height="200" src="'.Yii::app()->baseUrl .'/'. $url . '">
                                                                            <div class="text">
                                                                                <div class="inner">
                                                                                    <a href="#">
                                                                                        <i data-id="' . $count . '" link="../site/removeimage?pos='.$count.'&rowid='.$rowid.'" class="ace-icon fa fa-times red remove-image"></i>
                                                                                    </a>
                                                                                </div>
                                                                            </div>
                                                                        </div>
                                                                    </li>';
                                $data['html'] = $html;
                                $data_json = json_encode($data);
                                echo $data_json;
                        //        return $list_image;
                                die;
                        //        return true;
                            }
                    public function actionRemoveImage($pos, $rowid) {
                        $model = new UploadImage();
                        $list_image = json_decode($model->GetDatabase($rowid));
                //        $list_image_new = array_slice($list_image, $pos, 0);
                //        foreach ($list_image as $key => $value) {
                //            if ($key ==$pos) {
                //        echo var_dump($list_image);
                        if (count($list_image)>1) {
                            for ( $i=$pos; $i < count($list_image)-1; $i++) {
                                $list_image[$i] = '';
                                $list_image[$i] = $list_image[$i+1];
                //                if ($i == count($list_image)-1)
                //                    $list_image[$i +1] ='';
                //                echo var_dump($list_image);
                //                break;
                            }
                            $list_image[$i] = '';
                            unset($list_image[$i]);
                        }
                 else if (count ($list_image)== 1){ 
                     $list_image[0] = '';
                     unset ($list_image[0]);
                 }
     
// }
// echo var_dump($list_image);
// break;
            $model->SaveImage($list_image, $rowid);
            return true;
            }

                    public function actionItemView() {
                        $model = new UploadImage();
                        if ($this->checkLogin())
                        $this->render('itemview', array('model'=>$model));
                    }
                    //            don't use
                    public function actionMain() {
                                                $this->layout = FALSE;
                        $model = new SalePointForm();
                        $modelcontact = new ContactForm();
                        if (isset($_POST['ContactForm'])) {
                                                $modelcontact->attributes=$_POST['ContactForm'];
                            if($modelcontact->validate() && $modelcontact->contact()){
                //                                $this->redirect('index.php/site/main');     
                                Yii::app()->user->setFlash('contact','Thank you for contacting us. We will respond to you as soon as possible.');
                                                $this->refresh();
                        }}
                        $rows_salepoint = $model->getDatabase();
                        if (isset(Yii::app()->session['login']))
                        $row_salepoint = $model->getSalePoint(Yii::app()->session['saleId']);
                        else
                            $row_salepoint ='';

                        $this->render('main',array('data'=>$rows_salepoint,
                            'model'=>$modelcontact,
                            'row' =>$row_salepoint
                            ));
    }
                    public function bubbleSort($array, $column) {
        $tmp;
        if(is_array($array)) {
            foreach ($array as $key => $value) {
                for ($index = count($array)-1; $index > $key ; $index--) {
                    if ($array[$index][$column] < $array[$index-1][$column]) {
                        $tmp = $array[$index];
                        $array[$index] = $array[$index-1];
                        $array[$index-1] = $tmp;
                    }
                }
            }
            return $array;
        } else {
            return FALSE;    
        }
    }
public function actionGetTypeBusiness() {
            $type_businness = new TypeBusinessForm;
            $data = $type_businness->getDatabase();
                        $string = array();
        foreach ($data as $key => $value) {
            $string[$value['id']] = $value['name'];
        }
            return json_encode($string);
        }
}